package com.yjz.jvm.juc.ExecutorService;

import org.junit.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 定时线程池研究
 */
public class ScheledExecutorService {

    ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(1);


    ReentrantLock lock = new ReentrantLock();

    @Test
    public void test() throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.submit(() -> doSomething(0, 10, TimeUnit.SECONDS, 60,executorService));
        Thread.sleep(70000);
        System.out.println("线程池是否停止"+executorService.isShutdown());

    }

    /**
     * @param delay        延时多长的timeUnit再执行
     * @param cycle        执行周期
     * @param timeUnit     时间单位
     * @param lengthOfTime 时间长度
     * @param executorService 线程池 为了将这个线程池shutdown
     */
    public void doSomething(long delay, long cycle, TimeUnit timeUnit, int lengthOfTime,ExecutorService executorService) {
        Thread.currentThread().setName("doSomething线程");
        long delayTime = timeUnit.toNanos(delay);
        long endTime = timeUnit.toNanos(lengthOfTime);
        long execStartTime = System.nanoTime() + delayTime;
        long execEndTime = System.nanoTime() + endTime;
        while (true) {
            if (System.nanoTime() >= execStartTime && System.nanoTime() <= execEndTime) {
                System.out.println("runnable开始");
                try {
                    Thread.sleep(timeUnit.toMillis(cycle));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else if (System.nanoTime() > execEndTime) {
                executorService.shutdown();
                break;
            }
        }
        System.out.println("runnable结束");
    }
}
